<script setup>
import { ref, watch, defineProps, defineEmits } from 'vue'

// 定义 props
const props = defineProps({
  value: {
    type: String,
    default: "",
  },
  editable: {
    type: Boolean,
    default: false,
  },
})

// 定义 emits
const emit = defineEmits(['activeChange', 'input'])

// 响应式数据
const val = ref(["", "", "", "", "", "", "", ""])
const activeIndex = ref(props.editable ? 0 : undefined)

// 监听器
watch(activeIndex, () => {
  emit("activeChange", activeIndex.value)
})

watch(() => props.value, (newVal) => {
  if (val.value.join("") === newVal) {
    return
  }
  const valueArray = newVal.split("")
  if (props.editable) {
    activeIndex.value = valueArray.length
  }
  while (valueArray.length < 8) {
    valueArray.push("")
  }
  val.value = valueArray
}, { immediate: true })

watch(val, () => {
  emit("input", val.value.join(""))
}, { deep: true })

// 方法
const handleClickItem = (index) => {
  if (!props.editable) {
    return
  }
  activeIndex.value = index
}

const setValue = (char) => {
  val.value[activeIndex.value] = char
  if (activeIndex.value < 7) {
    activeIndex.value += 1
  }
}

const del = () => {
  val.value[activeIndex.value] = ""
  if (activeIndex.value > 0) {
    activeIndex.value -= 1
  }
}

// 暴露方法给父组件
defineExpose({
  setValue,
  del
})
</script>

<template>
  <div class="vnp-input-box">
    <ul>
      <li v-for="(item, index) in val" :key="index" :class="{ active: activeIndex === index }"
        @click="handleClickItem(index)">
        <span>{{ item }}</span>
      </li>
    </ul>
  </div>
</template>



<style lang="less" scoped>
.vnp-input-box {
  padding: 10px 0;
  border: 1px solid #d8d8d8;
  border-radius: 2px;
  color: #8d8d8d;
  font-size: 15px;
  text-align: center;

  ul {
    display: flex;
  }

  li {
    flex: 1;
    border-right: 1px solid #eaeaea;
    height: 28px;
    line-height: 28px;

    &:first-child {
      border-color: #a6a6a6;
      flex: 1.3;
    }

    &:last-child {
      border: none;
    }

    &.active {
      color: #1989fa;

      >span {
        height: 100%;
        width: 20px;
        display: inline-block;
        border-bottom: 1px solid #1989fa;
      }
    }
  }
}
</style>
